package com.tengju.bff.interfaces.data.settle;

import com.tengju.bff.interfaces.covercharge.dto.ChangeProfitDetailDTO;
import com.tengju.bff.interfaces.covercharge.dto.ProfitDetailDataDTO;
import com.tengju.bff.interfaces.covercharge.dto.ProfitSettleDetailReqDTO;
import com.tengju.bff.interfaces.covercharge.dto.ServiceDealResDTO;
import com.tengju.bff.interfaces.covercharge.enums.OperateTypeEnum;
import com.tengju.bff.interfaces.covercharge.enums.ProfitFromEnum;
import com.tengju.bff.interfaces.covercharge.enums.ProfitTypeEnum;
import com.tengju.bff.interfaces.covercharge.enums.ServiceAccountTypeEnum;
import com.tengju.bff.interfaces.covercharge.intf.IProfitSettleProvider;
import com.tengju.bff.interfaces.shared.ApiResponse;
import com.tengju.data.domain.model.report.*;
import com.tengju.data.domain.model.user.StarLevelEnum;
import com.tengju.data.domain.model.user.UserIdCode;
import com.tengju.data.domain.shared.CastUtil;
import com.tengju.data.domain.shared.Month;
import com.tengju.user.domain.model.user.UserInfo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.Arrays;

/**
 * @author chenhang
 * @Date 2021/1/15
 */
@Service
@Slf4j
@RequiredArgsConstructor(onConstructor_ = {@Autowired})

public class SettleBonusService {

    private final AchievementBonusRepository achievementBonusRepository;
    private final IProfitSettleProvider profitSettleProvider;
    private final BonusSettleRecordRepository bonusSettleRecordRepository;


    @Transactional(value = "dealerTransactionManager",rollbackFor = Exception.class)
    public void settleAchievementBonus(UserBonusResult userBonusResult, UserInfo userInfo, AchievementBonusDateConfig config) {
        long idCode = userBonusResult.getIdCode().getValue();
        StarLevelEnum curStarLevel = StarLevelEnum.NONE;
        if (userInfo != null && userInfo.getStarLevel() != null) {
            curStarLevel = StarLevelEnum.parseByStarLevel(userInfo.getStarLevel());
        }
        if (!userBonusResult.canSettle(curStarLevel, config)) {
            log.info("市场补贴不允许结算，idcode:{}",idCode);
            return;
        }
        BigDecimal bonus = userBonusResult.getBonus();
        Integer month = userBonusResult.getMonth();
        String uniqueId = genUniqNo(idCode,month);
        insertSettleRecord(uniqueId,month,bonus,idCode);
        achievementBonusRepository.updateBonusStatus(idCode,month, AchievementBonusStatusEnum.WAIT_SETTLE,AchievementBonusStatusEnum.SETTLE);
        doSettleAchievementBonus(idCode,bonus,month,uniqueId);
        log.info("市场补贴入账成功！idCode:{},profit:{},month:{}",idCode,bonus,month);
    }

    @Transactional(value = "dealerTransactionManager",rollbackFor = Exception.class)
    public void insertSettleRecord(String uniqueId, Integer month, BigDecimal bonus, Long idCode) {
        BonusSettleRecord record = new BonusSettleRecord(
                UserIdCode.of(idCode),
                new Month(month),
                uniqueId,
                new Month(LocalDate.now()),
                bonus
        );
        bonusSettleRecordRepository.insert(record);
    }

    private void doSettleAchievementBonus(Long idCode, BigDecimal bonus, Integer month, String uniqueId) {
        ProfitSettleDetailReqDTO profitSettleDetailReqDTO = new ProfitSettleDetailReqDTO();
        profitSettleDetailReqDTO.setProfitFrom(ProfitFromEnum.FROM_2);
        profitSettleDetailReqDTO.setUniqueId(uniqueId);
        ChangeProfitDetailDTO changeProfitDetailDTO = new ChangeProfitDetailDTO();
        ProfitDetailDataDTO profitDetailDataDTO = new ProfitDetailDataDTO();
        profitDetailDataDTO.setIdCode(idCode.intValue());
        profitDetailDataDTO.setAccountType(ServiceAccountTypeEnum.MANAGE_TYPE);
        profitDetailDataDTO.setOpType(OperateTypeEnum.SETTLE);
        profitDetailDataDTO.setTableId(0);
        profitDetailDataDTO.setOrderId(0L);
        profitDetailDataDTO.setReturnId(0L);
        profitDetailDataDTO.setGoodsId(0L);
        profitDetailDataDTO.setAmount(bonus);
        profitDetailDataDTO.setProfitTypeEnum(ProfitTypeEnum.team_in);
        profitDetailDataDTO.setDes("市场补贴入账");
        changeProfitDetailDTO.setSettleProfit(Arrays.asList(profitDetailDataDTO));
        profitSettleDetailReqDTO.setChangeProfit(changeProfitDetailDTO);
        ApiResponse<ServiceDealResDTO> serviceDealResDTOJsonResult = profitSettleProvider.clearSettlementByDetail(profitSettleDetailReqDTO);
        if (serviceDealResDTOJsonResult == null || !serviceDealResDTOJsonResult.isSuccess()) {
            throw new RuntimeException("市场补贴入账失败,idCode:" + idCode);
        }
    }


    public String genUniqNo(Object... params) {
        if (params.length == 0) {
            throw new RuntimeException("组建唯一id异常");
        }
        StringBuilder sb = new StringBuilder();
        for (Object param : params) {
            sb.append(CastUtil.castString(param)).append("_");
        }
        return sb.deleteCharAt(sb.length() - 1).toString();
    }
}
